#include<vector>
using namespace std;

struct TreeNode {
    TreeNode* left, * right;
};
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        return dfs(root)[0];
    }
    vector<int> dfs(TreeNode* root) {
        if (root == nullptr)return { 1,0 };
        vector<int> left = dfs(root->left), right = dfs(root->right);
        return { (left[0] && right[0] && abs(left[1] - right[1]) <= 1) ,max(left[1],right[1]) + 1 };
    }
};